<?php

declare(strict_types=1);

namespace App\Common\Libary\Third;

use App\Setting\Service\SettingConfigService;
use Hyperf\Stringable\Str;
use function Hyperf\Collection\collect;

class Wph
{
    //用户自己的appkey与secret
    protected $appkey = '657d7f4c';
    protected $appsecret = '7AF7E70949BF7AF97A19B7A332044264';
    protected $redirecturi = 'http://www.wikeyun.cn';
    protected $accessToken = '';
    protected $requestId = '';
    protected $refresh_token = '';
    protected $storeConfig;
    //超时时间
    protected $timeout = 20;
    protected $ctx = null;
    protected $storeId;
    //工具商的appkey与appsecret
    protected $oauthAppkey = '657d7f4c';
    protected $oauthAppsecret ='7AF7E70949BF7AF97A19B7A332044264';
    /**
     * 转链接的 externalInfo
     * @var
     */
    protected $externalInfo;

    protected $shopType = 5;

    /**
     * 是否强制使用官方
     * @var string
     */
    protected $forceUsePlat = false;

    /**
     * 官方联盟信息
     * @var array
     */
    protected $platUnionInfo = [];

    /**
     * pid
     * @var
     */
    public $pid ;

    protected $openId;

    public function __construct()
    {

        $this->requestId = Str::uuid();

        $config = container()->get(SettingConfigService::class)->getConfigMapByGroupKey('affiliate_oauth_config');

        $this->appkey = $config['wph_app_secret'];
        $this->appsecret = $config['wph_app_secret'];
    }

    public function transferChain($model,string $content,$urls = []): bool|string
    {
        $successCount = 0;
        foreach ($urls as $v){
            $tran = $this->transform([$v]);
            if(!empty($tran['urlInfoList'][0])){
                $res = $tran['urlInfoList'][0];
                $clickUrl = $res['url'];
                $onlyCommand = $res['onlyCommand'];
//                $rst[] = [
//                    'pwd' => $res['onlyCommand'],
//                    'url' => $res['url']
//                ];
                if($model == 4){
                    $text = $onlyCommand."\n".$clickUrl;
                }elseif($model == 3){
                    $text = $clickUrl;
                }else{
                    $text = $onlyCommand;
                }

                $content = str_replace($v,$text,$content);
                $successCount++;
            }
        }
        if($successCount > 0){
            return $content;
        }
        return false;
    }

    /**
     * 文案转化替换
     * @param string $content
     * @param array $urls
     * @return mixed
     */
    public function tranSearch($content,$urls = []){
        foreach ($urls as $k=>$v){
            $tran = $this->transform([$v]);
            $res = isset($tran['urlInfoList'][0]) ? $tran['urlInfoList'][0] : '';

            if(!empty($res)){
                $clickUrl = (string) $res['url'];
                !$clickUrl && logger()->debug("唯品会转链接失败{$v}",$tran);
                if($clickUrl){
                    $content = str_replace($v,$clickUrl,$content);
                }
            }else{
                return false;
            }
        }
        return $content;
    }

    /**
     * 根据唯品会链接生成联盟链接
     * @param unknown $requestId sub表uid
     * @param array $goodsIdList 商品id列表
     */
    public function transform($goodsIdList,$statParam='',$chanTag = ''){
        try {
            //1、获取服务客户端
            vendor('weipinhui.com.vip.adp.api.open.service.UnionUrlV2ServiceClient');
            $service = \com\vip\adp\api\open\service\UnionUrlV2ServiceClient::getService();
            //2、设置系统级调用参数，只需在程序开始调用前设置一次即可
            $ctx = \Osp\Context\InvocationContextFactory::getInstance();
            $ctx->setAppKey($this->oauthAppkey);//替换为你的appKey
            $ctx->setAppSecret($this->oauthAppsecret);//替换为你的appSecret
            $ctx->setAccessToken($this->accessToken);//替换为你的accessToken，通过Oauth认证时必填
            $ctx->setAppURL("https://gw.vipapis.com/");//正式环境
            //$ctx->setTimeOut(30)//超时时间，可选，默认30秒

            $genRequest = new \com\vip\adp\api\open\service\UrlGenRequest();
            $genRequest->openId = $this->openId ? $this->openId : 'default_open_id';
            $genRequest->realCall = true;
            $genRequest->adCode = 'vendoapi';
            $genRequest->genShortUrl = true;
            $genRequest->genAuthorityUrl = true;
            !$statParam && $statParam = $this->externalInfo;
            //3、调用API及返回
            $rtn = $service->genByVIPUrlWithOauth($goodsIdList,$chanTag ? $chanTag : $this->pid,$this->requestId,$statParam,$genRequest );
            return objtoarr($rtn);
        } catch (\Osp\Exception\OspException $e) {
            //4、捕获异常
            $res['code'] = $e->getReturnCode();
            $res['message'] = $e->getReturnMessage();
            return $res;
        }
    }

    /**
     * 获取指定商品id集合的商品信息
     * @param unknown $requestId sub表uid
     * @param array $goodsIdList 商品id列表
     */
    public function getByGoodsIdInfo($goodsId,$chanTag = ''){
        try {
            //1、获取服务客户端
            vendor('weipinhui.com.vip.adp.api.open.service.UnionGoodsV2ServiceClient');
            $service = \com\vip\adp\api\open\service\UnionGoodsV2ServiceClient::getService();
            //2、设置系统级调用参数，只需在程序开始调用前设置一次即可
            $ctx = \Osp\Context\InvocationContextFactory::getInstance();
            $ctx->setAppKey($this->oauthAppkey);//替换为你的appKey
            $ctx->setAppSecret($this->oauthAppsecret);//替换为你的appSecret
            $ctx->setAccessToken($this->accessToken);//替换为你的accessToken，通过Oauth认证时必填
            $ctx->setAppURL("https://gw.vipapis.com/");//正式环境

            $data = [
                'openId'    =>  $this->openId ? $this->openId : 'default_open_id',
                'realCall'  =>  true
            ];
            $request = new \com\vip\adp\api\open\service\GetByGoodsIdsRequest($data);
            $goodsIds2   =   $goodsId;
            $request->goodsIds=$goodsIds2;
            $request->queryDetail=true;
            $request->queryStock=true;
            $request->queryReputation=true;
            $request->queryStoreServiceCapability=true;
            $request->queryPMSAct=true;
            $request->queryPrepay=true;
            $request->extendBySpu=true;
            $request->requestId =  $this->requestId;
            $request->chanTag   =  $chanTag ? $chanTag : $this->pid;

            //3、调用API及返回
            $rtn = $service->getByGoodsIdsV2WithOauth($request);
            return objtoarr($rtn);
        } catch (\Osp\Exception\OspException $e) {
            //4、捕获异常
            $res['code'] = $e->getReturnCode();
            $res['message'] = $e->getReturnMessage();
            return $res;
        }
    }

    /**
     * 进行cps链接的解析
     * @param unknown $requestId sub表uid
     */
    public function urlService($content){
        try {
            //1、获取服务客户端
            vendor('weipinhui.com.vip.adp.api.open.service.UnionUrlV2ServiceClient');
            $service = \com\vip\adp\api\open\service\UnionUrlV2ServiceClient::getService();
            //2、设置系统级调用参数，只需在程序开始调用前设置一次即可
            $ctx = \Osp\Context\InvocationContextFactory::getInstance();
            $ctx->setAppKey($this->oauthAppkey);//替换为你的appKey
            $ctx->setAppSecret($this->oauthAppsecret);//替换为你的appSecret
            $ctx->setAccessToken($this->accessToken);//替换为你的accessToken，通过Oauth认证时必填
            $ctx->setAppURL("https://gw.vipapis.com/");//正式环境
            //$ctx->setTimeOut(30)//超时时间，可选，默认30秒
            //3、调用API及返回
            $data = [
                'content'   => $content,
                'source'    => $this->requestId,
                'requestId' => $this->requestId
            ];
            $array = new \com\vip\adp\api\open\service\VipLinkCheckReq($data);
            $rtn = $service->vipLinkCheckWithOuth($array);
            return objtoarr($rtn);
        } catch (\Osp\Exception\OspException $e) {
            //4、捕获异常
            $res['code'] = $e->getReturnCode();
            $res['message'] = $e->getReturnMessage();
            return $res;
        }
    }

    /**
     * 设置转链接的参数
     * @param unknown $uid
     * @param string $usePlat
     * @param array $ext
     * @return \app\common\controller\Jd
     */
    public function setExternalInfo($uid ,$ext = []):Wph{
        $this->openId = $data['subUid'] = $data['uid'] = $uid;
        $data['usePlat'] = true;

        if(!empty($ext)){
            $data = array_merge($data , $ext);
        }

        //最新机制 设置tranId
        $this->externalInfo = \App\Model\ItemsTransform::transform($uid ,$this->shopType ,$data);

        return $this;
    }

    /**
     * 获取订单信息列表
     * @param unknown $requestId sub表uid
     * @param string $updateTimeStart 订单更新时间
     * @param string $updateTimeEnd 订单更新结束时间
     * @param string $chanTag 推广位pid
     */
    public function orderList($appkey,$appsecret,$accessToken,$requestId,$updateTimeStart,$updateTimeEnd,$page = 1,$pageSize = 50){
        try {
            //1、获取服务客户端
            vendor('weipinhui.com.vip.adp.api.open.service.UnionOrderV2ServiceClient');
            $service = \com\vip\adp\api\open\service\UnionOrderV2ServiceClient::getService();
            //2、设置系统级调用参数，只需在程序开始调用前设置一次即可
            $ctx = \Osp\Context\InvocationContextFactory::getInstance ();
            $ctx->setAppKey($appkey);//替换为你的appKey
            $ctx->setAppSecret($appsecret);//替换为你的appSecret
            $ctx->setAccessToken($accessToken);//替换为你的accessToken，通过Oauth认证时必填
            $ctx->setAppURL("https://gw.vipapis.com/");//正式环境
            //$ctx->setTimeOut(30)//超时时间，可选，默认30秒
            //3、调用API及返回
            $array = [
                'page'=>$page,
                'pageSize'=>$pageSize,
                'requestId'=>$this->requestId,
            ];
            $array['updateTimeStart'] = $updateTimeStart*1000;
            $array['updateTimeEnd'] = $updateTimeEnd*1000;

            $data = new \com\vip\adp\api\open\service\OrderQueryModel($array);
            $rtn = $service->orderListWithOauth($data);
            return objtoarr($rtn);
        } catch (\Osp\Exception\OspException $e) {
            //4、捕获异常
            $res['code'] = $e->getReturnCode();
            $res['message'] = $e->getReturnMessage();
            return $res;
        }
    }

    public function setPid($pid)
    {
        $pid && $this->pid = $pid;
        return $this;
    }


    public function setAccessToken($token)
    {
        $this->accessToken = $token;
        return $this;
    }

}